package com.borrowed.book.config.shiro;

import com.borrowed.book.user.domain.SUser;
import com.borrowed.book.user.exception.UserNotExistException;
import com.borrowed.book.user.service.SUserService;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 微信登录认证、授权最终都是交给realm实现
 * @author jinbin
 */
public class WechatRealm extends AuthorizingRealm {
    private static Logger log = Logger.getLogger(com.borrowed.book.config.shiro.WechatRealm.class.getClass());

    @Autowired
    private SUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        WeChatToken token = (WeChatToken) authcToken;
        SUser userinfo=null;
        try {
            userinfo=userService.selectUserByOpenId(token.getOpenId());
            userinfo.setSessionKey(token.getSessionKey());
        }catch (UserNotExistException e){
            e.printStackTrace();
            throw new UnknownAccountException(e.getMessage(), e);
        }catch (Exception e){
            e.printStackTrace();
            log.error("微信用户["+token.getPrincipal()+"]登录失败");
            throw new AuthenticationException(e.getMessage(),e);
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userinfo,null,this.getName());
        return authenticationInfo;
    }

    /**
     * 重写supports,支持我们自定义的reamls
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token!=null&&token instanceof WeChatToken;
    }

    /**
     * 认证密码匹配调用方法
     */
    @Override
    protected void assertCredentialsMatch(AuthenticationToken authcToken,
                                          AuthenticationInfo info) throws AuthenticationException {
        return;
    }

}
